/*
Copyright 2013 Lin, Chung-Ming (aka Alva Lin. E-mail: alva0930@gmail.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.io.*;
import Jama.*;	// The 'Jama' package could be downloaded from: http://math.nist.gov/javanumerics/jama/
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.io.compress.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.*;

public class SingleHiddenLayerNNGradientBackpropagation
{
	public static class MapClass extends Mapper<IntWritable, Text, Text, DoubleArrayWritable>
	{
		private Matrix y;
		private Matrix theta1;
		private Matrix theta2;
		private Matrix theta2a;
		private Matrix theta1_grad;
		private Matrix theta2_grad;
		private int num_labels;

		public void setup(Context context) throws IOException, InterruptedException
		{
			String tempDir = context.getConfiguration().get("SingleHiddenLayerNN.TempDir");
			y = MatrixFunction.hdfsread(new Path(tempDir + "y"));
			theta1 = MatrixFunction.hdfsread(new Path(tempDir + "theta1"));
			theta2 = MatrixFunction.hdfsread(new Path(tempDir + "theta2"));
			num_labels = theta2.getRowDimension();
			theta2a = theta2.getMatrix(0, num_labels - 1, 1, theta2.getColumnDimension() - 1);
			theta1_grad = new Matrix(theta1.getRowDimension(), theta1.getColumnDimension());
			theta2_grad = new Matrix(num_labels, theta2.getColumnDimension());
		}

		public void map(IntWritable key, Text value, Context context) throws IOException, InterruptedException
		{
			int t = key.get();
			Matrix a1 = new Matrix(getDoubleArray(value.toString()), 1);
			Matrix z2 = a1.times(theta1.transpose());
			Matrix a2 = MatrixFunction.appendH(new Matrix(1, 1, 1), MatrixFunction.sigmoid(z2));
			Matrix z3 = a2.times(theta2.transpose());
			Matrix a3 = MatrixFunction.sigmoid(z3);

			Matrix y2 = new Matrix(1, num_labels);
			y2.set(0, (int)y.get(t, 0), 1);
			Matrix delta3 = a3.minus(y2);

			Matrix delta2 = delta3.times(theta2a).arrayTimes(MatrixFunction.sigmoidGradient(z2));

			theta1_grad.plusEquals(delta2.transpose().times(a1));
			theta2_grad.plusEquals(delta3.transpose().times(a2));
		}

		public void cleanup(Context context) throws IOException, InterruptedException
		{
			String dimension = theta1.getRowDimension() + "," + theta1.getColumnDimension() + "," + theta2.getRowDimension() + "," + theta2.getColumnDimension();
			double[] delta = MatrixFunction.unroll(theta1_grad, theta2_grad);
			context.write(new Text(dimension), new DoubleArrayWritable(delta));
		}
	}

	public static class ReduceClass extends Reducer<Text, DoubleArrayWritable, NullWritable, NullWritable>
	{
		public void reduce(Text key, Iterable<DoubleArrayWritable> values, Context context) throws IOException, InterruptedException
		{
			double[] delta = null;
			for (DoubleArrayWritable val : values)
			{
				double[] da = val.getDoubleArray();
				if (null == delta)
				{
					delta = new double[da.length];
				}
				for (int i = 0; i < delta.length; i++)
				{
					delta[i] += da[i];
				}
			}
			int[] dimension = getIntArray(key.toString());
			int theta1Size = dimension[0] * dimension[1];
			Matrix theta1_grad = MatrixFunction.reshape(delta, 0, theta1Size - 1, dimension[0], dimension[1]);
			Matrix theta2_grad = MatrixFunction.reshape(delta, theta1Size, delta.length - 1, dimension[2], dimension[3]);

			Configuration conf = context.getConfiguration();
			String tempDir = conf.get("SingleHiddenLayerNN.TempDir");
			if (false == conf.getBoolean("mapred.compress.map.output", false))
			{
				MatrixFunction.hdfswrite(new Path(tempDir + "theta1_grad"), theta1_grad);
				MatrixFunction.hdfswrite(new Path(tempDir + "theta2_grad"), theta2_grad);
			}
			else
			{
				Class<?> codecClass = conf.getClass("mapred.map.output.compression.codec", null);
				CompressionCodec codec = (CompressionCodec)ReflectionUtils.newInstance(codecClass, conf);
				MatrixFunction.hdfswrite(new Path(tempDir + "theta1_grad"), theta1_grad, SequenceFile.CompressionType.BLOCK, codec);
				MatrixFunction.hdfswrite(new Path(tempDir + "theta2_grad"), theta2_grad, SequenceFile.CompressionType.BLOCK, codec);
			}
		}
	}

	public static void main(String[] args) throws Exception
	{
		Configuration conf = new Configuration();

		String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
		String tempDir = otherArgs[0];
		conf.set("SingleHiddenLayerNN.TempDir", tempDir);
		if (otherArgs.length > 1)
		{
			conf.setBoolean("mapred.compress.map.output", true);
			conf.setClass("mapred.map.output.compression.codec", Class.forName(otherArgs[1]), CompressionCodec.class);
		}

		Path outputPath = new Path(tempDir + "output");
		FileSystem.get(conf).delete(outputPath, true);
		Job job = new Job(conf, "SingleHiddenLayerNNGradientBackpropagation");
		job.setJarByClass(SingleHiddenLayerNNGradientBackpropagation.class);
		job.setMapperClass(MapClass.class);
		job.setReducerClass(ReduceClass.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(DoubleArrayWritable.class);
		job.setOutputKeyClass(NullWritable.class);
		job.setOutputValueClass(NullWritable.class);
		job.setInputFormatClass(SequenceFileInputFormat.class);
		job.setOutputFormatClass(TextOutputFormat.class);
		SequenceFileInputFormat.addInputPath(job, new Path(tempDir + "X"));
		TextOutputFormat.setOutputPath(job, outputPath);
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}

	private static int[] getIntArray(String line)
	{
		String[] strings = line.split(",", 0);
		int[] numbers = new int[strings.length];
		for (int i = 0; i < strings.length; i++)
		{
			numbers[i] = Integer.parseInt(strings[i]);
		}
		return numbers;
	}

	private static double[] getDoubleArray(String line)
	{
		String[] strings = line.split(",", 0);
		double[] numbers = new double[strings.length];
		for (int i = 0; i < strings.length; i++)
		{
			numbers[i] = Double.parseDouble(strings[i]);
		}
		return numbers;
	}
}